from django.shortcuts import render, HttpResponse, redirect
from books import models
from django.http import JsonResponse
from django import forms
from django.forms import widgets
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.contrib import auth
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


# Create your views here.
class Userinfo(forms.Form):
    user = forms.CharField(max_length=32, error_messages={"required": "该字段不能为空"}, label='用户名')
    pwd = forms.CharField(max_length=32, label='密码', error_messages={"required": "该字段不能为空"})
    re_pwd = forms.CharField(max_length=32, label='确认密码', error_messages={"required": "该字段不能为空"})
    email = forms.EmailField(max_length=32, label='邮件', error_messages={"required": "该字段不能为空"})

    # 局部钩子校验
    def clean_user(self):
        val = self.cleaned_data.get("user")
        user = models.UserInfo.objects.filter(username=val).first()
        if not user:
            return val
        else:
            raise ValidationError("该用户已注册")

    # 全局钩子校验
    def clean(self):
        pwd = self.cleaned_data.get("pwd")
        re_pwd = self.cleaned_data.get("re_pwd")
        if pwd and re_pwd:
            if pwd == re_pwd:
                return self.cleaned_data
            else:
                raise ValidationError("两次密码不一致！")
        else:
            return self.cleaned_data


def register(request):
    if request.method == 'POST':
        response = {"user": None, "msg": None}
        form = Userinfo(request.POST)
        if form.is_valid():
            response["user"] = form.cleaned_data.get('user')
            user = form.cleaned_data.get('user')
            pwd = form.cleaned_data.get('pwd')
            email = form.cleaned_data.get('emali')
            models.UserInfo.objects.create_user(username=user, password=pwd, email=email)
        else:
            response["msg"] = form.errors
            print(form.errors)
        return JsonResponse(response)

    return render(request, 'register.html')


def login(request):
    if request.method == "POST":
        response = {"user": False}
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        user = auth.authenticate(username=user, password=pwd)
        if user:
            auth.login(request, user)  # request.user 当前登录对象
            response['user'] = True
        return JsonResponse(response)

    return render(request, 'login.html')


def index(request):
    if request.method == "POST":
        choise = request.POST.get("choise")
        if choise == "author":
            author_obj = list(models.Author.objects.all().values_list('name', 'age', 'nid'))
            paginator = Paginator(author_obj, 10)
            try:
                current_page = int(request.POST.get("current_pag", 1))
                author_obj = paginator.page(current_page).object_list
            except Exception as e:
                print(e)
                author_obj = paginator.page(1).object_list
            return JsonResponse({"author_obj": author_obj, "page_num": paginator.num_pages})
        elif choise == "publish":
            publish_obj = list(models.Publish.objects.all().values_list('name', 'city', 'email', 'nid'))
            paginator = Paginator(publish_obj, 10)
            try:
                current_page = int(request.POST.get("current_pag", 1))
                publish_obj = paginator.page(current_page).object_list
            except Exception as e:
                print(e)
                publish_obj = paginator.page(1).object_list
            print(publish_obj)
            return JsonResponse({"publish_obj": publish_obj, "page_num": paginator.num_pages})
        elif choise == "books":
            import datetime
            # time = datetime.date.today()
            # models.Book.objects.create(title='红楼梦',publishDate=time,price=56,publish_id=2)
            data_books = []
            book_obj = models.Book.objects.all()
            for book in book_obj:
                book_author = models.Book.objects.filter(nid=book.pk).values_list('authors__name')
                data_books.append(
                    [book.title, book.publishDate, book.price, book.publish.name, list(book_author), book.nid])
            paginator = Paginator(data_books, 10)
            try:
                current_page = int(request.POST.get("current_pag", 1))
                data_books = paginator.page(current_page).object_list
            except Exception as e:
                print(e)
                data_books = paginator.page(1).object_list
            return JsonResponse({"book_obj": data_books, "page_num": paginator.num_pages})

    return render(request, 'index.html')


def author_add(request):
    if request.method == "POST":
        author = request.POST.get("author")
        age = request.POST.get("age")
        is_author = models.Author.objects.filter(name=author).first()
        if not author or not age:
            return JsonResponse({"is_author": None})
        if is_author:
            return JsonResponse({"is_author": True})
        else:
            models.Author.objects.create(name=author, age=age)
    return HttpResponse('ok')


def publish_add(request):
    if request.method == "POST":
        respon = {"is_null": False, "is_publish": False}
        publish_name = request.POST.get("publish_name")
        city_name = request.POST.get("city_name")
        email_name = request.POST.get("email_name")
        is_publish = models.Publish.objects.filter(name=publish_name).first()
        if not publish_name or not city_name or not email_name:
            respon["is_null"] = True
        elif is_publish:
            respon['is_publish'] = True
        else:
            models.Publish.objects.create(name=publish_name, city=city_name, email=email_name)
        return JsonResponse(respon)
    return HttpResponse('ok')


def s_books(request):
    author = list(models.Author.objects.all().values_list('nid', 'name'))
    publish = list(models.Publish.objects.all().values_list('nid', 'name'))
    return JsonResponse({"author": author, "publish": publish})


def book_add(request):
    if request.method == "POST":
        # print(request.POST)
        respon = {"is_null": False, "is_books": False}
        book_name = request.POST.get("book_name")
        publish_date = request.POST.get("publish_date")
        book_price = request.POST.get("book_price")
        publish_id = request.POST.get("pulish_id")
        author_id = request.POST.get("author_id")
        try:
            author_id = [x.split("=")[1] for x in author_id.strip().split("&")]
        except Exception:
            pass
        book_obj = models.Book.objects.filter(title=book_name).first()
        if not book_name or not publish_date or not book_price or not publish_id or not author_id:
            respon['is_null'] = True
        elif book_obj:
            respon['is_books'] = True
        else:
            book = models.Book.objects.create(title=book_name, publishDate=publish_date, price=book_price,
                                              publish_id=publish_id)
            book.authors.add(*author_id)
        return JsonResponse(respon)

    return HttpResponse('ok')


def delete(request):
    print(request.POST)
    if request.method == "POST":
        current_btn = request.POST.get("current_btn")
        current_id = request.POST.get("current_id")
        if current_btn == "d_author":
            models.Author.objects.filter(nid=current_id).delete()
            return JsonResponse({"current_l": "d_author"})
        elif current_btn == "d_publish":
            models.Publish.objects.filter(nid=current_id).delete()
            return JsonResponse({"current_l": "d_publish"})
        elif current_btn == "d_books":
            models.Book.objects.filter(nid=current_id).delete()
            return JsonResponse({"current_l": "d_books"})
        else:
            return JsonResponse({"current_l": "xxx"})

    return HttpResponse("ok")


def edit(request):
    if request.POST.get("edit_type") == "books":
        current_id = request.POST.get("current_id")
        author = request.POST.get("author").split(",")
        publish = request.POST.get("publish")
        price = request.POST.get("price")
        publish_date = request.POST.get("publish_date")
        book_title = request.POST.get("book_title")
        publish_obj = models.Publish.objects.filter(name=publish).first()
        book_obj = models.Book.objects.filter(nid=current_id).first()
        # book_obj.update(title=book_title, publishDate=publish_date,price=price,publish_id=publish_obj.pk)
        book_obj.title = book_title
        book_obj.publishDate = publish_date
        book_obj.price = price
        book_obj.publish_id = publish_obj.pk
        try:
            book_obj.save()
        except  ValidationError:
            return JsonResponse({"status": "ValidationError"})
        book_obj.authors.clear()
        for name in author:
            name = models.Author.objects.filter(name=name).first()
            book_obj.authors.add(name)
    elif request.POST.get("edit_type") == "author":
        current_id = request.POST.get("current_id")
        author_age = request.POST.get("author_age")
        author_name = request.POST.get("author_name")
        models.Author.objects.filter(nid=current_id).update(name=author_name, age=author_age)
    elif request.POST.get("edit_type") == "publish":
        current_id = request.POST.get("current_id")
        publish_email = request.POST.get("publish_email")
        publish_city = request.POST.get("publish_city")
        publish_name = request.POST.get("publish_name")
        models.Publish.objects.filter(nid=current_id).update(name=publish_name, city=publish_city, email=publish_email)

    return HttpResponse("ok")


def select(request, condition, name):
    if condition == "author":
        author_books = models.Author.objects.filter(name=name).values("book__title", "book__publishDate",
                                                                      "book__price", "book__publish__name")

        return render(request, 'author_Detalles.html', {"author_books": author_books})
    elif condition == "publish":
        book_nid = models.Publish.objects.filter(name=name).values_list("book__nid")
        book_list = []
        for book_id in book_nid:
            book_obj = models.Book.objects.filter(nid=book_id[0])
            book_author = book_obj.values_list("authors__name")
            book_detail = book_obj.values_list("title", "publishDate", "price", "publish__name")
            author_list = list(i[0] for i in book_author)
            try:
                if author_list[0] == None: author_list[0] = ""
            except IndexError:
                return HttpResponse("该出版社还没有书籍")
            book_list.append({"author": author_list, "book": book_detail})

        return render(request, "publish_detalles.html", {"book_list": book_list})


def manager(request):
    return render(request, 'manager.html')
